import { Component, ViewChild } from '@angular/core';

import { NavParams, ViewController, Content } from 'ionic-angular';

import { ContactChooseService } from './choose.service';

import { Storage } from '@ionic/storage';

import _ from 'lodash';

@Component({
  selector: 'page-contact-choose',
  templateUrl: 'choose.html',
  providers: [ContactChooseService]
})
export class ContactChoosePage {
	moa_page_name: any = "page-contact-choose";
	moa_page_explain = "组织树";

  // 返回组织结构如下：
  // {
  //   name: "广发基金",
  //   orgid:"gffunds",
  //   reorgid:"0"
  //   full_name:"广发基金"
  // }

  // 返回岗位信息结构如下：
  // {
  //   name: "董事长",
  //   orgid:"gsld",
  //   titleid:"dsz",
  //   full_name:"董事长"
  // }

  // 返回人员信息结构如下：
  // {
  //   empid:"A938493525",
  //   name:"冯镜蒯",
  //   orgid:"xtyfz",
  //   titleid:"ybyg",
  //   full_name:"冯镜蒯"
  // }

  _ = _;

  @ViewChild(Content) content: Content;

  segmentType = "2";

  // 存储选择列表状态
  stackData: any = [];
  // 当前显示数据
  listData: any = [];
  // 查询搜索
  queryText = '';
  // 存储数据
  storeList: any = [];
  // 组织列表数据
  orgList: any = [];
  // 选中的选项
  selectedList: any = [];

  searchCondition = {
    reorgid: "",
    orgid: "",
    titleid: ""
  };

  // 是否只能人
  isSelectUser = false;

  // 是否只允许选一个人
  isSelectOne = false;

  preSelectItem: any = {};

  reorgid = "root";

  orgid = "0";

  titleid = null;

  isSaveQueryText = false;

  /**
   * 预置人员
   */
  //参与人
  empnames;
  empnamesId;

  // 默认参与人
  defaultEmpnames =[];
  defaultEmpnamesId =[];

  // 是否显示组织数，0 不显示 1显示
  isSelAddr;

  // 人员选择对象数组{"empname":,"empnameId":,"isChecked":}
  empList = [
  ];

  // 是否全选
  isCheckAll = false;


  constructor(
    public navParams: NavParams,
    public storage: Storage,
    public viewCtrl: ViewController
  ) {

    this.reorgid = this.navParams.get("reorgid") ? this.navParams.get("reorgid") : this.reorgid;
    this.orgid = this.navParams.get("orgid") ? this.navParams.get("orgid") : this.orgid;
    this.titleid = this.navParams.get("titleid") ? this.navParams.get("titleid") : this.titleid;

    let selected = this.navParams.get("selected");
    this.isSelectUser = this.navParams.get("isSelectUser") ? true : this.isSelectUser;
    this.isSelectOne = this.navParams.get("isSelectOne") ? true : this.isSelectOne;

    this.isSaveQueryText = this.navParams.get("isSaveQueryText") ? true : this.isSaveQueryText;

    if (selected && selected.length > 0) {
      this.selectedList = selected;
    }
    this.initData();

    let that = this;
    if (this.isSaveQueryText) {
      this.storage.get("queryText").then(q => {
        that.queryText = q;
        that.updateList();
      });
    }

    /**
     * 预置人员
     */
    this.empnames = this.navParams.get('empnames') ? this.navParams.get('empnames') : [];
    this.empnamesId = this.navParams.get('empnamesId') ? this.navParams.get('empnamesId') : [];
    this.defaultEmpnames = this.navParams.get('defaultEmpnames') ? this.navParams.get('defaultEmpnames') : [];
    this.defaultEmpnamesId = this.navParams.get('defaultEmpnamesId') ? this.navParams.get('defaultEmpnamesId') : [];

    if (this.empnamesId && this.empnamesId.length > 0) {
      this.segmentType = "1";
    }

    // 构建人员选择对象数组
    for (var i = 0; i < this.empnames.length; i++) {
      let temp = {
        "empname": this.empnames[i],
        "empnameId": this.empnamesId[i],
        "isChecked": _.indexOf(this.defaultEmpnamesId, this.empnamesId[i]) > -1 ? true : false
      };
      this.empList.push(temp);
    }

    if (this.segmentType ==='2' && this.empnamesId.length <= 0) {

    }
  }

  /**
   * [initData 初始化页面数据]
   */
  initData() {
    this.storage.get('contact-org-list').then(data => {
      this.storeList = data;
      this.stackData = [];
      this.listData = this.getOrgList(this.reorgid, this.orgid, this.titleid);
      // this.listData = this.getOrgList("gffunds", "xxjsb", null);
      // this.listData = this.getOrgList("gffunds", "gsld", null);
      // this.listData = this.getOrgList(null, "xtyfz", "ybyg");
    });
  }

  /**
   * [getOrgList 缓存搜索需要展示的数据]
   * @param {[type]} reorgid [上一层组织id]
   * @param {[type]} orgid   [组织id]
   * @param {[type]} titleid [岗位id]
   */
  getOrgList(reorgid, orgid, titleid) {
    let _this = this;
    let result: any = [];
    // 重新读取当前需要渲染的列表
    this.orgList = [];
    this.orgList = _.cloneDeep(this.storeList);
    // 如果有titleid,则是查询第三层
    if (titleid) {
      let l1: any = _.find(_this.orgList, {
        name: 'contact-list-org-third-' + orgid + "-" + titleid
      });
      // 如果下级没数据，则返回;
      if (!l1) {
        return;
      }
      l1 = l1["list"];
      l1 = _.remove(l1, null);
      _.each(l1, function(item, index) {
        l1[index].type = 'user';
        l1[index].name = item.emname;
        l1[index].isSelected = _this.checkIsSelected(l1[index], null);;
        l1[index].isShowSub = false;
      });
      result = l1;
    } else {
      // 否则，查询第一、二层
      var l11: any = _.find(_this.orgList, {
        name: 'contact-list-org-first-' + reorgid + '-' + orgid
      });
      var l12: any = _.find(_this.orgList, {
        name: 'contact-list-org-second-' + reorgid + '-' + orgid
      });
      l11 = l11 ? l11['list'] : [];
      l12 = l12 ? l12['list'] : [];
      var l = _.concat(l12, l11);
      l = _.remove(l, null);
      _.each(l, function(item, index) {
        l[index].type = item.titleid ? 'title' : 'dept';
        var sub = [];
        var l2, l3;
        if (item.titleid) {
          l2 = _.find(_this.orgList, {
            name: 'contact-list-org-third-' + item.orgid + "-" + item.titleid
          });
          sub = l2 ? l2.list : null;
        } else {
          l2 = _.find(_this.orgList, {
            name: 'contact-list-org-first-' + item.reorgid + "-" + item.orgid
          });
          l3 = _.find(_this.orgList, {
            name: 'contact-list-org-second-' + item.reorgid + "-" + item.orgid
          });
          l2 = l2 ? l2['list'] : [];
          l3 = l3 ? l3['list'] : [];
          sub = _.concat(l3, l2);
        }
        item.isSelected = _this.checkIsSelected(l[index], null);
        let topIsSelected = false;
        sub = _.remove(sub, null);
        _.each(sub, function(item2, index) {
          if (item2.empid) {
            sub[index].name = item2.emname;
            sub[index].type = 'user';
            sub[index].isShowSub = false;
          } else {
            sub[index].name = item2.titleid ? item2.titlename : item2.orgname;
            sub[index]['subList'] = [];
            sub[index].type = item2.titleid ? 'title' : 'dept';
            sub[index].isShowSub = false;
          }
          sub[index].isSelected = _this.checkIsSelected(sub[index], null);
          // 如果有一个选中，则顶层展开
          if (sub[index].isSelected) {
            topIsSelected = true;
          }
        });
        item.subList = sub;
        item.name = item.titleid ? item.titlename : item.orgname;
        // item.isShowSub = item.isSelected || topIsSelected;
        item.isShowSub = false;
        result.push(item);
      });
    }
    this.searchCondition = {
      reorgid: reorgid,
      orgid: orgid,
      titleid: titleid
    }
    return result;
  }

  // 刷新当前展示列表
  refreshList() {
    this.listData = this.getOrgList(this.searchCondition.reorgid, this.searchCondition.orgid, this.searchCondition.titleid);
  }

  /**
   * [expand 点击展开按钮，判断是否展开还是选中，还是跳转]
   * @param {[type]} type [description]
   * @param {[type]} item [description]
   */
  expand(type, item) {
    // 如果是顶级点击，则判断是否选中或者展开
    if (item.type == 'user') {
      this.onChange(item, null);
    } else {
      if (type == 'top') {
        if (item.subList && item.subList.length > 0) {
          item.isShowSub = !item.isShowSub;
        } else {
          // item.isSelected = !item.isSelected;
        }
      } else {
        // 如果是二级点击，判断是是否要选中或者跳转
        if (item.subList) {
          this.stackData.push({
            top: this.content.scrollTop,
            data: this.searchCondition
          });
          this.listData = this.getOrgList(item.reorgid ? item.reorgid : null, item.orgid, item.titleid ? item.titleid : null);
        } else {
          // item.isSelected = !item.isSelected;
        }
      }
    }
  };

  /**
   * [goBack 当选中到下一层及的时候出现返回上你一层级按钮]
   */
  goBack() {
    let item: any = _.last(this.stackData);
    // this.listData = item.data;
    this.searchCondition = item.data;
    this.refreshList();
    this.content.scrollTo(0, item.top, 100);
    this.stackData.pop();
  };

  checkIsSelected(item, topItem) {
    let pickItem = this.pickProperty(item, true);
    let isSelectCurrent = _.find(this.selectedList, pickItem) ? true : false;
    if (isSelectCurrent) {
    }
    if (topItem) {
      let pickTopItem = this.pickProperty(topItem, true);
      let isSelectTop = _.find(this.selectedList, pickTopItem) ? true : false;
      if (isSelectTop) {
      }
      return isSelectTop;
    } else {
      return isSelectCurrent;
    }
  };

  pickProperty(item, isSimple) {
    let pickItem;
    if (isSimple) {
      if (item.empid || item.loginid) {
        pickItem = _.pick(item, ['empid']);
      } else if (item.titleid) {
        pickItem = _.pick(item, ['orgid', 'titleid', 'type']);
      } else {
        pickItem = _.pick(item, ['orgid', 'type']);
      }
    } else {
      if (item.empid) {
        pickItem = _.pick(item, ['name', 'empid', 'titleid', 'orgid', 'loginid', 'type', 'full_orgname']);
      } else {
        pickItem = _.pick(item, ['type', 'name', 'orgid', 'reorgid', 'titleid', 'full_orgname']);
      }
    }
    return pickItem;
  }

  addSelectedList(item) {
    this.selectedList.push(this.pickProperty(item, false));
    let temp = _.find(this.empList, {empnameId: item.loginid});
    if (temp) {
      temp.isChecked = true;
    }
  }

  removeSelectedList(item) {
    _.remove(this.selectedList, this.pickProperty(item, true));
    let temp = _.find(this.empList, {empnameId: item.loginid});
    if (temp) {
      temp.isChecked = false;
    }
  }

  /**
   * [onChange 当列表数据被选中改变状态时候触发方法]
   * @param {[type]} item [description]
   */
  onChange(item, topItem) {
    console.log(item);

    let _this = this;
    this.preSelectItem.isSelected = false;
    item.isSelected = !item.isSelected;
    if (this.isSelectOne) {
      if (item.isSelected) {
        // 把所有选中的去掉。
        this.selectedList = [];
        this.addSelectedList(item);
        var arr = document.getElementsByTagName("page-contact-choose")[0].getElementsByTagName('input');
        var arrValue = [];
        var i = 0;
        for (var n = 0; n < arr.length; n++) {
          if (arr[n].type == 'checkbox') {
            arr[n].checked = false;
          }
        }
        this.preSelectItem = item;
      } else {
        item.isSelected = false;
        this.removeSelectedList(item);
      }
    } else {
      // 处理所有选中事件
      // item.isSelected = !this.checkIsSelected(item, topItem);
      // item.isSelected = !item.isSelected;

      // 如果是选中的，则放到选中数据
      if (item.isSelected) {
        this.addSelectedList(item);
        if (item.subList) {
          _.each(item.subList, function(iItem, index) {
            _this.removeSelectedList(iItem);
          });
        }
      } else {
        // 如果是取消，则移除
        this.removeSelectedList(item);
      }
      // 处理选中，或者取消下层选中，修改顶层状态
      if (topItem && topItem.subList.length > 1) {
        if (_.find(topItem.subList, { isSelected: false })) {
          topItem.isSelected = false;
          _this.removeSelectedList(topItem);
        } else {
          topItem.isSelected = true;
          _this.addSelectedList(topItem);
        }
        if (topItem.isSelected === false) {
          _.each(topItem.subList, function(tsItem, index) {
            _this.removeSelectedList(tsItem);
            if (tsItem.isSelected) {
              _this.addSelectedList(tsItem);
            }
          });
        } else {
          _.each(topItem.subList, function(tsItem, index) {
            _this.removeSelectedList(tsItem);
          });
        }
      }

      // 处理选中顶层，下面层级选中
      if (item.subList) {
        _.each(item.subList, function(subitem, index) {
          item.subList[index].isSelected = item.isSelected;
        });
      }
    }
  };

  /**
   * [updateList 输入搜索内容，更新列表]
   */
  updateList() {
    let _that = this;
    let qt = this.queryText.toLowerCase();
    if (this.queryText == '') {
      this.initData();
    } else {
      this.stackData = [];
      let tempList = [];
      this.storage.get('contact-org-list').then(orgList => {
        _.each(orgList, function(org, i) {
          if (org.name.indexOf("contact-list-org-third") > -1) {
            _.each(org.list, function(item, ii) {
              if (item.full_orgname.indexOf("群组/") == 0) { } else {
                if (_.findIndex(tempList, {
                  empid: item.empid
                }) == -1) {
                  if (item.emname.toLowerCase().indexOf(qt) > -1 || (item.full_pinyin && item.full_pinyin.indexOf(qt) > -1)) {
                    item.isSelected = _that.checkIsSelected(item, null);
                    item.name = item.emname;
                    item.type = 'user';
                    item.subList = [];
                    item.isShowSub = false;
                    tempList.push(item);
                  }
                }
              }
            })
          }
        });
        this.listData = tempList;
      });
    }
  }

  /**
   * [removeSelectedItem 点击移除已经选中的节点]
   * @param {[type]} item [description]
   */
  removeSelectedItem(item) {
    this.removeSelectedList(item);
    if (this.queryText.toLowerCase()) {
      this.updateList();
    } else {
      this.refreshList();
    }
  }

  /**
   * [complete 点击完成，把选中数据传回上一层页面]
   */
  complete() {
    // let result = _.filter(this.listData, { isSelected: true });
    this.dismiss(this.selectedList);
    if (this.isSaveQueryText) {
      this.storage.set("queryText", this.queryText);
    }
  }

  dismiss(data?: any) {
    // using the injected ViewController this page
    // can "dismiss" itself and pass back data
    this.viewCtrl.dismiss(data);
  }

  /**
   * 预置人员
   */
  /*complete() {
    // let result = _.filter(this.listData, { isSelected: true });
    this.dismiss({ "defaultEmpnames": this.defaultEmpnames, "defaultEmpnamesId": this.defaultEmpnamesId });
  }*/

  /*dismiss(data?: any) {
    // using the injected ViewController this page
    // can "dismiss" itself and pass back data
    this.viewCtrl.dismiss(data);
  }*/

  //原来checked 状态是ture的改成false并在默认选择数组中移除,
  //状态false的改成true并添加到默认选择数组
  selectChange(index) {
    if (!this.isSelectOne) { // 多选
      if (this.empList[index].isChecked) {
        this.empList[index].isChecked = false;
        this.defaultEmpnames = _.pull(this.defaultEmpnames, this.empList[index].empname);
        this.defaultEmpnamesId = _.pull(this.defaultEmpnamesId, this.empList[index].empnameId);
        let item = _.find(this.selectedList, {loginid: this.empList[index].empnameId});
        if (item) {
          this.removeSelectedItem(item);
        }
      } else {
        this.empList[index].isChecked = true;
        this.defaultEmpnames.push(this.empList[index].empname);
        this.defaultEmpnamesId.push(this.empList[index].empnameId);
        console.log(this.listData);

        this.storage.get('contact-user-list').then(data => {
          console.log(data);
          let user = _.find(data, {"loginid": this.empList[index].empnameId});
          if (user) {
            let delfaultUser = {
              empid: user["empid"],
              loginid: user["loginid"],
              name: user["emname"],
              orgid: user["orgid"],
              titleid: user["titleid"],
              type: "user"
            };
            this.selectedList.push(delfaultUser);
            this.initData();
          }
        });
      }
    } else { // 单选
      if (this.empList[index].isChecked) {
        this.empList[index].isChecked = false;
        this.defaultEmpnames = [];
        this.defaultEmpnamesId = [];
        let item = _.find(this.selectedList, {loginid: this.empList[index].empnameId});
        if (item) {
          this.removeSelectedItem(item);
        }
      } else {
        if(this.defaultEmpnamesId.length > 0) { // 将已选的改成未选
          let temp_select_emp = _.find(this.empList,{"empnameId" : this.defaultEmpnamesId[0]});
          if (temp_select_emp) {
            temp_select_emp.isChecked = false;
          }
        }

        this.empList[index].isChecked = true;
        this.defaultEmpnames = _.concat([],this.empList[index].empname);
        this.defaultEmpnamesId =_.concat([],this.empList[index].empnameId);

        this.storage.get('contact-user-list').then(data => {
          console.log(data);
          let user = _.find(data, {"loginid": this.empList[index].empnameId});
          console.log("user", user);
          if (user) {
            let delfaultUser = {
              empid: user["empid"],
              loginid: user["loginid"],
              name: user["emname"],
              orgid: user["orgid"],
              titleid: user["titleid"],
              type: "user"
            };
            this.selectedList = [];
            this.selectedList.push(delfaultUser);
            this.initData();
          }
        });
      }
    }
  }

  /**
   * [checkALLorNot description]
   */
  checkALLorNot(){
    var that = this;
    this.isCheckAll = !this.isCheckAll;

    _.forEach(this.empList, function(data){
      data.isChecked = that.isCheckAll;
    })

    if(this.isCheckAll){ // 全选
      this.defaultEmpnames = this.empnames;
      this.defaultEmpnamesId = this.empnamesId;

    } else { // 取消选择
      this.defaultEmpnames=[];
      this.defaultEmpnamesId=[];
    }

  }
}
